//
//  XXDeviceManager.swift
//  Example
//
//  Created by xx on 2025/3/20.
//

import UIKit

class XXDevice:NSObject{
    var type:String = ""
    var mac:String = ""
    var topics:Array<String>  = []
    var state = 0 // 0未知  1 在线 2 离线
}

class XXDeviceManager {
    
    public static var shared = XXDeviceManager()
    
    var deviceList:Array<XXDevice> = []
    
    private init() {
        XXListenerManager.shared.registerRoute(XXMQTTRout.didReceiveMessage.rawValue) { [weak self] massage in
            if let topic = massage?.dic?.string("topic"),let msg = massage?.dic?.string("msg"){
                if topic == XXTOPIC.PUBLIC.SEARCH_A.rawValue{
                    self?.onMassage(msg)
                }
            }
        }
        
        XXListenerManager.shared.registerRoute(XXMQTTRout.connectState.rawValue) { [weak self] massage in
            if massage == "1"{
                self?.refresh()
            }
        }
        
        Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] timer in
            self?.refresh()
        }
    }
    // 处理消息回调
    func onMassage(_ msg:String){
        let components = msg.components(separatedBy: "/")
        if components.count > 2{
            let topics:Array<String> = Array(components[2...])
            var isHave = false
            for device in self.deviceList{
                if device.type == components[0] && device.mac == components[1]{
                    isHave = true
                    device.state = 1
                    device.topics = topics
                    break
                }
            }
            if isHave == false{
                let device = XXDevice()
                device.type = components[0]
                device.mac = components[1]
                device.topics = topics
                device.state = 1
                self.deviceList.append(device)
            }
            
        }
    }
    // 获取设备列表
    func getDeviceList(_ type:String?) -> Array<XXDevice>{
        if let t = type{
            var devices:Array<XXDevice> = []
            for d in self.deviceList{
                if d.type == t{
                    devices.append(d)
                }
            }
            return devices
        }else{
            return self.deviceList
        }
    }
    
    // 刷新设备
    func refresh(){
        for device in self.deviceList{
            device.state = 2
        }
        XXMQTT.shared.send(topic:  XXTOPIC.PUBLIC.SEARCH.rawValue, msg: "")
    }
}
